package com.athena.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.athena.common.core.domain.entity.SysDept;
import com.athena.common.helper.LoginHelper;
import com.athena.common.utils.StreamUtils;
import com.athena.common.utils.StringUtils;
import com.athena.common.core.page.TableDataInfo;
import com.athena.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.athena.crm.constant.CommonConstant;
import com.athena.crm.domain.*;
import com.athena.crm.domain.bo.CrmCustomerToHighSeasBo;
import com.athena.crm.domain.vo.CrmCluePoolVo;
import com.athena.crm.domain.vo.CrmCustomerVo;
import com.athena.crm.mapper.CrmCustomerFollrecordsMapper;
import com.athena.crm.mapper.CrmCustomerMapper;
import com.athena.system.mapper.SysDeptMapper;
import com.athena.system.service.ISysDeptService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.filefilter.FalseFileFilter;
import org.springframework.stereotype.Service;
import com.athena.crm.domain.bo.CrmCustomerHighSeasBo;
import com.athena.crm.domain.vo.CrmCustomerHighSeasVo;
import com.athena.crm.mapper.CrmCustomerHighSeasMapper;
import com.athena.crm.service.ICrmCustomerHighSeasService;

import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * CRM客户公海Service业务层处理
 *
 * @author ruoyi
 * @date 2023-09-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class CrmCustomerHighSeasServiceImpl implements ICrmCustomerHighSeasService {

    private final CrmCustomerHighSeasMapper baseMapper;

    private final CrmCustomerMapper crmCustomerMapper;

    private final ISysDeptService sysDeptService;

    private final CrmCustomerFollrecordsMapper crmCustomerFollrecordsMapper;

    /**
     * 查询CRM客户公海
     */
    @Override
    public CrmCustomerHighSeasVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询CRM客户公海列表
     */
    @Override
    public TableDataInfo<CrmCustomerHighSeasVo> queryPageList(CrmCustomerHighSeasBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<CrmCustomerHighSeas> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(CrmCustomerHighSeas::getUpdateTime);
        Page<CrmCustomerHighSeasVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<CrmCustomerHighSeasVo> crmCustomerHighSeasVos = result.getRecords();
        for (CrmCustomerHighSeasVo crmCustomerHighSeasVo:crmCustomerHighSeasVos) {
            String deptPaht = sysDeptService.getDeptPath(crmCustomerHighSeasVo.getFormerDeptId(), "");
            crmCustomerHighSeasVo.setFormerDept(deptPaht);
        }
        return TableDataInfo.build(result);
    }



    /**
     * 查询CRM客户公海列表
     */
    @Override
    public List<CrmCustomerHighSeasVo> queryList(CrmCustomerHighSeasBo bo) {
        LambdaQueryWrapper<CrmCustomerHighSeas> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(CrmCustomerHighSeas::getUpdateTime);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<CrmCustomerHighSeas> buildQueryWrapper(CrmCustomerHighSeasBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<CrmCustomerHighSeas> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getFormerHead()), CrmCustomerHighSeas::getFormerHead, bo.getFormerHead());
        if(bo.getFormerDeptId() != null) {
            lqw.eq(StringUtils.isNotBlank(bo.getFormerDeptId().toString()), CrmCustomerHighSeas::getFormerDeptId, bo.getFormerDeptId());
        }
        lqw.like(StringUtils.isNotBlank(bo.getName()), CrmCustomerHighSeas::getName, bo.getName());
        lqw.like(StringUtils.isNotBlank(bo.getCompanyName()), CrmCustomerHighSeas::getCompanyName, bo.getCompanyName());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), CrmCustomerHighSeas::getType, bo.getType());
        lqw.eq(StringUtils.isNotBlank(bo.getPhone()), CrmCustomerHighSeas::getPhone, bo.getPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getContacts()), CrmCustomerHighSeas::getContacts, bo.getContacts());
        lqw.eq(bo.getRealityFollowRecords() != null, CrmCustomerHighSeas::getRealityFollowRecords, bo.getRealityFollowRecords());
        lqw.eq(StringUtils.isNotBlank(bo.getLatestFollowRecords()), CrmCustomerHighSeas::getLatestFollowRecords, bo.getLatestFollowRecords());
        return lqw;
    }

    /**
     * 新增CRM客户公海
     */
    @Override
    public Boolean insertByBo(CrmCustomerHighSeasBo bo) {
        CrmCustomerHighSeas add = BeanUtil.toBean(bo, CrmCustomerHighSeas.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改CRM客户公海
     */
    @Override
    public Boolean updateByBo(CrmCustomerHighSeasBo bo) {
        CrmCustomerHighSeas update = BeanUtil.toBean(bo, CrmCustomerHighSeas.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(CrmCustomerHighSeas entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除CRM客户公海
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public int customerToCustomerHighSeas(CrmCustomerToHighSeasBo bbo) {
        List<CrmCustomer> crmCustomers = new ArrayList<>();
        List<CrmCustomerHighSeas> crmCustomerHighSeass = new ArrayList<>();
        List<CrmCustomerFollrecords> crmCustomerFollrecordss = new ArrayList<>();
        String[] ids = bbo.getIds().split(",");
        List<String> idLis = Arrays.asList(ids);
        List<CrmCustomerVo> crmCustomerVos = crmCustomerMapper.selectVoBatchIds(idLis);
        for (CrmCustomerVo crmCustomerVo:crmCustomerVos) {
            //客户公海记录
            CrmCustomerHighSeas crmCustomerHighSeas = new CrmCustomerHighSeas();
            crmCustomerHighSeas.setCompanyName(crmCustomerVo.getComName());
            crmCustomerHighSeas.setName(crmCustomerVo.getName());
            crmCustomerHighSeas.setFormerHead(crmCustomerVo.getHead());
            crmCustomerHighSeas.setFormerDeptId(crmCustomerVo.getDeptId());
            crmCustomerHighSeas.setContacts(crmCustomerVo.getContacts());
            crmCustomerHighSeas.setType(crmCustomerVo.getType());
            crmCustomerHighSeas.setPhone(crmCustomerVo.getPhone());
            crmCustomerHighSeas.setCustomerId(crmCustomerVo.getId() + "");
            log.info("{}, {}", crmCustomerVo.getId(), crmCustomerVo.getName());
            crmCustomerHighSeass.add(crmCustomerHighSeas);
            //客户操作记录
            CrmCustomerFollrecords crmCustomerFollrecords = new CrmCustomerFollrecords();
            crmCustomerFollrecords.setCustomerId(crmCustomerVo.getId() + "");
            crmCustomerFollrecords.setFlowType(CommonConstant.FOLLOW_TYPE_OPERATE_LOG);
            crmCustomerFollrecords.setFollowContent("转客户公海[" + crmCustomerVo.getName() + "]");
            crmCustomerFollrecords.setFollowUser(LoginHelper.getLoginUser().getUsername());
            crmCustomerFollrecordss.add(crmCustomerFollrecords);

            CrmCustomer crmCustomer = BeanUtil.toBean(crmCustomerVo, CrmCustomer.class);
            crmCustomers.add(crmCustomer);
        }
        for (CrmCustomer crmCustomer:crmCustomers) {
            //更新客户负责人、部门
            crmCustomer.setFormerHead(crmCustomer.getHead());
            crmCustomer.setFormerDeptId(crmCustomer.getDeptId());
            crmCustomer.setHead(null);
            crmCustomer.setDeptId(null);
            crmCustomer.setCustomerStatus("客户公海");
        }
        crmCustomerFollrecordsMapper.insertBatch(crmCustomerFollrecordss);
        baseMapper.insertBatch(crmCustomerHighSeass);
        crmCustomerMapper.insertOrUpdateBatch(crmCustomers);
        return 1;
    }

    @Override
    public int customerSeasToCustomerHigh(CrmCustomerToHighSeasBo bbo) {
        log.info("客户公海ID {} 转客户", bbo.getIds());
        String[] ids = bbo.getIds().split(",");
        List<CrmCustomerHighSeas> crmCustomerHighSeass = baseMapper.selectBatchIds(Arrays.asList(ids));
        List<String> customerIds =  crmCustomerHighSeass.stream().map(CrmCustomerHighSeas::getCustomerId).collect(Collectors.toList());
        List<CrmCustomerVo> crmCustomerVos = crmCustomerMapper.selectVoBatchIds(customerIds);
        List<CrmCustomer> crmCustomers = new ArrayList<>();
        List<CrmCustomerFollrecords> crmCustomerFollrecordss = new ArrayList<>();
        for (CrmCustomerVo crmCustomerVo:crmCustomerVos) {
            log.info("客户ID: {}, name: {}", crmCustomerVo.getId(), crmCustomerVo.getName());
            CrmCustomer crmCustomer = BeanUtil.toBean(crmCustomerVo, CrmCustomer.class);
            crmCustomer.setCustomerStatus("客户");
            crmCustomer.setHead(LoginHelper.getLoginUser().getUsername());
            crmCustomer.setDeptId(LoginHelper.getLoginUser().getDeptId());
            crmCustomer.setUpdateBy(LoginHelper.getLoginUser().getUsername());
            crmCustomer.setUpdateTime(new Date());
            crmCustomers.add(crmCustomer);
            //客户操作记录
            CrmCustomerFollrecords crmCustomerFollrecords = new CrmCustomerFollrecords();
            crmCustomerFollrecords.setCustomerId(crmCustomerVo.getId() + "");
            crmCustomerFollrecords.setFlowType(CommonConstant.FOLLOW_TYPE_OPERATE_LOG);
            crmCustomerFollrecords.setFollowContent("公海转客户[" + crmCustomerVo.getName() + "]");
            crmCustomerFollrecords.setFollowUser(LoginHelper.getLoginUser().getUsername());
            crmCustomerFollrecordss.add(crmCustomerFollrecords);
        }
        crmCustomerFollrecordsMapper.insertBatch(crmCustomerFollrecordss);
        baseMapper.deleteBatchIds(Arrays.asList(ids));
        crmCustomerMapper.insertOrUpdateBatch(crmCustomers);
        return 1;
    }
}
